<script setup lang="ts">
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import { NGrid } from 'naive-ui';
  import JsonEditorVue from 'json-editor-vue3';
  import { useFormRules, useNaiveForm } from '@/hooks/common/form';
  import { fetchGetUserList } from '@/service/api';
  import { $t } from '@/locales';
  import {
    enableStatusOptions,
    operationStatusRecord,
    userGenderOptions,
  } from '@/constants/business';
  import { useCommonStore } from '@/store/modules/common';
  import { formatDate, handleCopy, isPermission } from '@/utils/tools';
  import { useAuthStore } from '@/store/modules/auth';
  import uploadImg from '@/components/common/upload-img.vue';
  import type { Api } from '@/typings/api';
  defineOptions({
    name: 'UserOperateDrawer',
  });

  interface Props {
    /** the type of operation */
    operateType: NaiveUI.TableOperateType;
    /** the edit row data */
    rowData?: any;
  }
  const authStore = useAuthStore();
  const h = window.innerHeight * 0.8;

  const props: any = defineProps<Props>();

  interface Emits {
    (e: 'submitted', mode: any): void;
  }

  const emit = defineEmits<Emits>();

  const visible = defineModel<boolean>('visible', {
    default: false,
  });

  const { formRef, validate, restoreValidation } = useNaiveForm();
  const { defaultRequiredRule } = useFormRules();

  const title = computed(() => {
    const titles: Record<NaiveUI.TableOperateType, string> = {
      add: $t('page.systemControl.operationApi.add'),
      edit: $t('page.systemControl.operationApi.edit'),
      details: $t('page.systemControl.operationApi.details'),
    };
    return titles[props.operateType as NaiveUI.TableOperateType];
  });

  // type Model = Pick<
  //   Api.User.UserListOperate
  // >;
  type Model = any;

  const model: any = reactive(createDefaultModel());

  function createDefaultModel(): Model {
    return {
      name: '',
      phone: null,
      role: 'user',
      email: '',
      credit: '',
      frozenCredit: '',
      createdAt: null,
      updatedAt: null,
      deletedAt: null,
      avatar: '',
    };
  }

  type RuleKey = Extract<keyof Model, 'userName' | 'status'>;

  const rules: Record<RuleKey, App.Global.FormRule> = {
    userName: defaultRequiredRule,
    status: defaultRequiredRule,
  };

  /** the enabled role options */
  const roleOptions = ref<CommonType.Option<string>[]>([
    { label: '管理员', value: 'admin' },
    { label: '用户', value: 'user' },
  ]);

  // async function getRoleOptions() {
  //   const { error, data } = await fetchGetUserList({
  //     id:
  //   });

  //   if (!error) {
  //     const options = data.map((item: any) => ({
  //       label: item.roleName,
  //       value: item.roleCode
  //     }));

  //     // the mock data does not have the roleCode, so fill it
  //     // if the real request, remove the following code
  //     const userRoleOptions = model.userRoles.map((item: any) => ({
  //       label: item,
  //       value: item
  //     }));
  //     // end

  //     roleOptions.value = [...userRoleOptions, ...options];
  //   }
  // }

  function handleInitModel() {
    Object.assign(model, createDefaultModel());

    if (props.operateType !== 'add' && props.rowData) {
      Object.assign(model, props.rowData);
      delete model.index;
      delete model.updatedAt;
      // delete model.createdAt
      delete model.deletedAt;
      model.event = JSON.parse(model.event);
    }
  }

  function closeDrawer() {
    visible.value = false;
  }

  async function handleSubmit() {
    await validate();
    // request
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted', model);
  }

  watch(visible, () => {
    if (visible.value) {
      handleInitModel();
      restoreValidation();
      // getRoleOptions();
    }
  });
  const tagMap: Record<Api.User.operationStatus, NaiveUI.ThemeColor> = {
    add: 'primary',
    update: 'info',
    delete: 'success',
  };
  const tag = (row: any) => {
    let boo = true;
    let label = '';
    if (row.name !== 'add' && row.name !== 'update' && row.name !== 'delete') {
      label = $t('page.systemControl.operationApi.any');
      boo = false;
    } else {
      label = $t(operationStatusRecord[row.name as Api.User.operationStatus]);
    }

    return {
      label,
      boo,
    };

    // (
    //   <NTag type={boo ? tagMap[row.name as Api.User.operationStatus] : 'error'}>
    //     {label}
    //   </NTag>
    // );
  };
</script>

<template>
  <NDrawer
    v-model:show="visible"
    display-directive="show"
    placement="bottom"
    :height="h"
  >
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" size="small">
        <!--
 <NGrid x-gap="50" y-gap="25" :cols="4">
          <NGi>
            <NFormItem
              :label="$t('page.systemControl.operationApi.operateUser')"
              path="name"
            >
              {{ model.metadata?.operateUserData?.name }}
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.systemControl.operationApi.operateUserPhone')"
              path="phone"
            >
              {{ model.metadata?.operateUserData?.phone }}
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.systemControl.operationApi.operateUserId')"
              path="id"
            >
              {{ model.metadata?.operateUserData?.id }}
              <icon-local-copy
                style="cursor: pointer"
                @click="handleCopy(model.metadata?.operateUserData?.id)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.systemControl.operationApi.operateId')"
              path="id"
            >
              {{ model.metadata?.id }}
              <icon-local-copy
                style="cursor: pointer"
                @click="handleCopy(model.metadata?.id)"
              />
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.userData.userGenerate.status')"
              path="status"
            >
              <NTag
                :type="
                  tag(rowData).boo
                    ? tagMap[rowData.name as Api.User.operationStatus]
                    : 'error'
                "
                >{{ tag(rowData).label }}</NTag
              >
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.userData.userList.createdAt')"
              path="createdAt"
            >
              {{ formatDate(props.rowData.createdAt, 'YYYY-MM-DD HH:mm:ss') }}
            </NFormItem>
          </NGi>
          <NGi>
            <NFormItem
              :label="$t('page.userData.userList.updateRemarks')"
              path="updateRemarks"
            >
              {{ model.metadata?.updateRemarks }}
            </NFormItem>
          </NGi>
        </NGrid>
-->

        <NCard
          v-if="model.type === 'update'"
          :title="$t('page.systemControl.operationApi.title')"
          size="huge"
        >
          <NTable
            v-if="model.event"
            :bordered="false"
            :single-line="false"
            striped
            style="width: 1000px"
          >
            <thead>
              <tr>
                <th>更改项</th>
                <th>原先值</th>
                <th>-</th>
                <th>更新值</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, key) in model.event" :key="item + key">
                <td>{{ item.key }}</td>
                <td>{{ item.oldValue }}</td>
                <td>>>></td>
                <td>{{ item.newValue }}</td>
              </tr>
            </tbody>
          </NTable>
        </NCard>

        <!--
 <NFormItem :label="$t('page.manage.user.userGender')" path="userGender">
          <NRadioGroup v-model:value="model.userGender">
            <NRadio v-for="item in userGenderOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
-->
      </NForm>
      <template #footer>
        <NSpace :size="32">
          <NButton type="primary" @click="closeDrawer">{{
            $t('common.close')
          }}</NButton>
          <!-- <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton> -->
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
